import React,{Component}from 'react';
import { Dimensions,StyleSheet , Image,TouchableHighlight, ScrollView,View, Text,RefreshControl} from 'react-native';
import Swiper from 'react-native-swiper';
import UserManager from '../common/UserManager';
import Constants from '../common/Constants';
import { AppInfo,queryAppList, insertAppInfos } from "../database/AppInfo";
import {validateLongTokenApi} from "../api/LoginApi"
import ToastUtils from '../components/ToastUtils';
import {PullView} from 'react-native-pull';

export default class HomePage extends Component{

    constructor(props) {
        super(props);
        this.state = {
          userInfo: {},
          installedList: [],
          refreshing:false,
        
        };

        this.getDefaultValue()
       
      }

    async getDefaultValue(){
    
      let user = await  UserManager.getUserInfo()
      this.setState({userInfo: user})
      console.log("user is", this.state.userInfo.UserName)
      let installedList = queryAppList()
      this.setState({installedList: installedList})

    }

    

    componentDidMount(){
      this.getDefaultValue()
    }

    didClickItem(item){

    

      // if(item.appHisId == 1198 ){

        this.props.navigation.navigate('WebviewPage',{item: item});
        
      // }else{
      //   this.props.navigation.navigate('RFIDPage',{item: item});
      // }
      // 

      

    }


    componentDidUpdate(){

    
     
      this.validateLongTicket()
    
    }


    validateLongTicket(){

      validateLongTokenApi().then(async (resp)=>{
        console.log("validateLongToke:", res)

        if(resp.Success){
          console.log( 'validateLongTicket', resp.Context.Ticket)
        await  UserManager.setUserInfo(resp.Result )
        await  UserManager.setTicket({"ticket": resp.Context.Ticket})
         that.getLongTicket()
          

        }
        // getLongToken();
    }).catch((error)=>{
    //  ToastUtils.showToast( error);
   });
       

    }

    getAppListView(){
      this.state.installedList.map(function(elem, index) {
        var baseImg='data:image/png;base64,' + elem.appLogo;
        console.log("elem.appName===============", elem.appName)
        return(

          <Text style={styles.boxText}>{elem.appName}</Text>
          );
      });
    }

    getAppListView(){
      const that = this
      var boxs =this.state.installedList.map(function(elem, index) {
        var baseImg='data:image/png;base64,' + elem.appLogo;
        return (
          <TouchableHighlight key={elem.key} style={[styles.touchBox, index % 3 === 2 ? styles.touchBox2 : styles.touchBox1]} underlayColor="#eee" onPress={()=> that.didClickItem(elem)}>
            <View style={styles.boxContainer}>
              <Text style={styles.boxText}>{elem.appName}</Text>
              <Image
                     style={styles.boxIcon}
                      source={{uri: baseImg}}
                    /> 
    
              {/* {elem.isFA ? <IconFA size={elem.size} name={elem.icon} style={[styles.boxIcon,{color:elem.color}]} /> :
                <Icon size={elem.size} name={elem.icon} style={[styles.boxIcon,{color:elem.color}]} />} */}
            </View>
          </TouchableHighlight>
        );
      });
      return boxs;
    }

     //下拉视图开始刷新时调用
     onStartRefresh() {

      if (this.state.refreshing === false) {
        this.setState({refreshing: true});
        this.getDefaultValue()

          //5秒后结束刷新
          setTimeout( ()=>{
            this.setState({refreshing: false});
          }, 2000)

      }
  }

    render(){

      const that = this

      

        return (
            <ScrollView style={styles.mainView} title={this.props.title}  //下拉刷新
            refreshControl={
              <RefreshControl 
              tintColor={'red'}
              titleColor={'brown'}
              title={'正在刷新......'}
              refreshing={this.state.refreshing} onRefresh={this.onStartRefresh.bind(this)} />
            }
            >

              <View>
            <Swiper height={180} showsButtons={false} autoplay={true}
              activeDot={<View style={{backgroundColor: 'rgba(255,255,255,0.8)', width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3}} />}
              >
              <TouchableHighlight onPress={()=> this.didClickItem(0)}>
                <View style={styles.slide}>
                  <Image style={styles.image}  source={{uri:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Faliyunzixunbucket.oss-cn-beijing.aliyuncs.com%2Fjpg%2Fe667b1e4574cd8c86fedac6adb18c930.jpg%3Fx-oss-process%3Dimage%2Fresize%2Cp_100%2Fauto-orient%2C1%2Fquality%2Cq_90%2Fformat%2Cjpg%2Fwatermark%2Cimage_eXVuY2VzaGk%3D%2Ct_100&refer=http%3A%2F%2Faliyunzixunbucket.oss-cn-beijing.aliyuncs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628215082&t=f9f3f2e187d98fe2550a81badddbd1de'}} />
                  {/* <Text style={styles.slideText}>Day1: Timer</Text> */}
                </View>
              </TouchableHighlight>
              <TouchableHighlight onPress={()=> this.didClickItem(1)}>
                <View style={styles.slide}>
                  <Image style={styles.image} source={{uri:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pxcodes.com%2Fd%2Ffile%2F6d4bbc07f8b07e288b5d6549932d85d5.jpg&refer=http%3A%2F%2Fwww.pxcodes.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628215083&t=d452498e9a332e82b9b9d1bb57c584df'}} />
                  {/* <Text style={styles.slideText}>Day2: Weather</Text> */}
                </View>
              </TouchableHighlight>
            </Swiper>
            <View style={styles.touchBoxContainer}>
              
                   {this.getAppListView()}
                
              
              
            </View>

           

            </View>
           
            
           </ScrollView>

         
         


        );
    }
}

const styles = StyleSheet.create({
    container:{
        flexGrow:1,
        backgroundColor: "#ff0000"
      },
      mainView: {
        marginTop: 0,
      },
      touchBoxContainer:{
      
        flexDirection: 'row',
        flexWrap: 'wrap',
        width: Constants.deviceWidth,
        borderWidth: Constants.pixel,
        borderColor: '#CCC',
        // backgroundColor: "#ff0000"
        // borderTopWidth: Tool.pixel,
        // borderTopColor: '#CCC',
        // borderLeftWidth: Tool.pixel,
        // borderLeftColor:'#ccc',
        // borderRightWidth: Tool.pixel,
        // borderRightColor:'#ccc',
      },
      touchBox:{
          width: Constants.deviceWidth / 3 - Constants.pixel * 3,
          height: Constants.deviceWidth / 3 - Constants.pixel * 3,
          backgroundColor: '#fff',
          borderWidth: Constants.pixel,
          borderColor:'#ccc',
          // backgroundColor: "#ff0000"
      },
      touchBox1:{
        borderWidth: Constants.pixel,
        borderColor:'#ccc',
        // borderBottomWidth: Tool.pixel,
        // borderBottomColor:'#ccc',
        // borderLeftWidth: Tool.pixel,
        // borderLeftColor:'#ccc',
        // borderRightWidth: Tool.pixel,
        // borderRightColor:'#ccc',
        // borderTopWidth: Tool.pixel,
        // borderTopColor:'#ccc',
  
      },
      touchBox2:{
        borderWidth: Constants.pixel,
        borderColor:'#ccc',
        // borderBottomWidth: Tool.pixel,
        // borderBottomColor:'#ccc',
        // borderLeftWidth: Tool.pixel,
        // borderLeftColor:'#ccc',
        // borderRightWidth: Tool.pixel,
        // borderRightColor:'#ccc',
        // borderTopWidth: Tool.pixel,
        // borderTopColor:'#ccc',
      },
      boxContainer:{
        alignItems:'center',
        justifyContent:'center',
        width: Constants.deviceWidth / 3,
        height:Constants.deviceWidth / 3,
        // backgroundColor: "#ff0000"
      },
      boxIcon:{
        position:'relative',
        top:-10,
        width: 50,
        height: 50,
      },
      boxText:{
        position:'absolute',
        bottom:15,
        width:Constants.deviceWidth / 3 - 1,
        textAlign:'center',
        left: 0,
        backgroundColor:'transparent',
      },
      slide: {
        flexGrow: 1,
        height: 180,
        justifyContent: 'center',
        alignItems: 'center',
      },
      slideText:{
        position:'absolute',
        bottom: 0,
        paddingTop:5,
        paddingBottom:5,
        backgroundColor:'rgba(255,255,255,0.5)',
        width: Constants.deviceWidth,
        textAlign:'center',
        fontSize: 12,
      },
      image:{
        width: Constants.deviceWidth,
        flexGrow: 1,
        alignSelf: 'stretch',
      },
  });
  